package cn.ydxiaoshuai.sample;

import cn.ydxiaoshuai.common.Config;
import cn.ydxiaoshuai.common.PhysiognomyBD;
import cn.ydxiaoshuai.common.ReptileBean;
import cn.ydxiaoshuai.util.ReptileHttpUtil;
import com.alibaba.fastjson.JSON;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.List;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReptileSampleNew {
    public static void main(String[] args) throws Exception {
        //图片路径
        String image = "/Users/xiaoshuai/Downloads/FaceDetect/SignTest/8.png";
        //上传图片获取sign
        ReptileBean bean = getApi(image,true);
        //根据sign请求面相地址获取面相数据
        String result = getPhysiognomy(bean.getData().getSign());
        //获取所需数据
        PhysiognomyBD physiognomyBD = JSON.parseObject(result,PhysiognomyBD.class);
        System.out.println("五官相说");
        PhysiognomyBD.FaceResult faceResult = physiognomyBD.getFaceResult();
        List<PhysiognomyBD.FaceFate> faceFates =  faceResult.getFaceFate();
        PhysiognomyBD.FaceTop faceTop = faceResult.getFaceTop();
        System.out.println( " 眼睛： " +faceTop.getEye().getValue() + " 关键词：" + faceTop.getEye().getDesc());
        System.out.println( " 眉毛： " +faceTop.getBrow().getValue() + " 关键词：" + faceTop.getBrow().getDesc());
        System.out.println( " 嘴巴： " +faceTop.getMouth().getValue() + " 关键词：" + faceTop.getMouth().getDesc());
        System.out.println( " 鼻子： " +faceTop.getNose().getValue() + " 关键词：" + faceTop.getNose().getDesc());
        System.out.println( " 脸型： " +faceTop.getShape().getValue() + " 关键词：" + faceTop.getShape().getDesc());

        System.out.println( " 福气值： " +physiognomyBD.getFaceShare().getHappyLot());

        List<String> faceAbstracts = faceResult.getFaceAbstract();
        System.out.println(" 面相概述：");
        for (String faceAbstract : faceAbstracts) {
            System.out.println(faceAbstract.toString());
        }


    }
    /**
     * 上传图片获取SIGN
     * @param image 图片本地路径
     * @return String
     * @throws Exception
     */
    public static String getApi(String image) throws Exception{
        String result = ReptileHttpUtil.uploadFile(Config.ROOT_URL, image);
        return result;
    }
    /**
     * 上传图片获取SIGN
     * @param image 图片本地路径
     * @param isBean true false都可以 只是为了区别一个返回字符串 一个返回对象
     * @return @see ReptileBean
     * @throws Exception
     */
    public static ReptileBean getApi(String image,boolean isBean) throws Exception{
        String result = getApi(image);
        System.out.println(result);
        ReptileBean bean = JSON.parseObject(result, ReptileBean.class);
        return bean;
    }
    /**
     * 爬取面相相关内容
     * @param sign 签名值
     * @return String
     * @throws Exception
     */
    public static String getPhysiognomy(String sign) throws Exception {
        String url = Config.YANZHI_URL.replace("SIGN", sign);
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        //屏蔽日志信息
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
                "org.apache.commons.logging.impl.NoOpLog");
        java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

        //支持JavaScript
        webClient.getOptions().setThrowExceptionOnScriptError(false);//;//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);//是否启用CSS
        webClient.getOptions().setJavaScriptEnabled(true);//启用JS
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX

        HtmlPage rootPage = webClient.getPage(url);
        //设置一个运行JavaScript的时间
        webClient.waitForBackgroundJavaScript(8000);
        String html = rootPage.asXml();
        Document document = Jsoup.parse(html);
        //获取第index个script脚本 目前是第四个 index=3
        Elements elements = document.getElementsByTag("script").eq(3);
        //unicode 转一下中文
        String data = unicodeDecode(elements.get(0).toString());
        //截取window.tplData = 的值  目前是window.tplData
        int startIndex = data.indexOf("window.tplData =")+17;
        int endIndex = data.lastIndexOf("};")+1;
        String result = data.substring(startIndex,endIndex);
        return unicodeDecode(result);
    }

    /**
     * unicode 转中文
     * @param string
     * @return
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }
}
